import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: HomeView,
  },
  {
    path: '/filter',
    name: 'Filter',
    component: () => import('../views/filter.vue'),
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/AboutView.vue'),
  },
  {
    path: '/dir',
    name: 'Directive',
    component: () => import('../views/directive.vue'),
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/transition',
    name: 'transition',
    component: () => import('../views/transition.vue'),
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('../views/search.vue'),
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

// 导航守卫

router.beforeEach((to, from, next) => {
  console.log(to.name)
  if (to.name === 'Login') {
    next()
  } else {
    const token = store.state.token
    if (token) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          filePath: to.fullPath,
        },
      })
    }
  }
})

export default router
